﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RDPCOMAPILib;
using ShiQuan.Remoting.Helper;
using System.Runtime.InteropServices;

namespace ShiQuan.Remoting
{
    public class UCRemoteSharer : UserControl
    {
        private System.Windows.Forms.ToolStrip sysToolBar;
        private System.Windows.Forms.ToolStripButton tbbStart;
        private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
        private System.Windows.Forms.RichTextBox richTextBox1;

        /// <summary> 
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary> 
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源，为 true；否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (this.m_pRdpSession != null)
            {
 
            }
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region 组件设计器生成的代码

        /// <summary> 
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(UCRemoteSharer));
            this.sysToolBar = new System.Windows.Forms.ToolStrip();
            this.tbbStart = new System.Windows.Forms.ToolStripButton();
            this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
            this.richTextBox1 = new System.Windows.Forms.RichTextBox();
            this.sysToolBar.SuspendLayout();
            this.SuspendLayout();
            // 
            // sysToolBar
            // 
            this.sysToolBar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.tbbStart,
            this.toolStripSeparator1});
            this.sysToolBar.Location = new System.Drawing.Point(0, 0);
            this.sysToolBar.Name = "sysToolBar";
            this.sysToolBar.Size = new System.Drawing.Size(809, 25);
            this.sysToolBar.TabIndex = 0;
            this.sysToolBar.Text = "toolStrip1";
            // 
            // tbbStart
            // 
            this.tbbStart.Image = ((System.Drawing.Image)(resources.GetObject("tbbStart.Image")));
            this.tbbStart.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.tbbStart.Name = "tbbStart";
            this.tbbStart.Size = new System.Drawing.Size(49, 22);
            this.tbbStart.Text = "开启";
            // 
            // toolStripSeparator1
            // 
            this.toolStripSeparator1.Name = "toolStripSeparator1";
            this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25);
            // 
            // richTextBox1
            // 
            this.richTextBox1.BackColor = System.Drawing.SystemColors.Info;
            this.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.richTextBox1.Location = new System.Drawing.Point(0, 25);
            this.richTextBox1.Name = "richTextBox1";
            this.richTextBox1.ReadOnly = true;
            this.richTextBox1.Size = new System.Drawing.Size(809, 468);
            this.richTextBox1.TabIndex = 1;
            this.richTextBox1.Text = "";
            // 
            // UCRemoteSharer
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this.richTextBox1);
            this.Controls.Add(this.sysToolBar);
            this.Name = "UCRemoteSharer";
            this.Size = new System.Drawing.Size(809, 493);
            this.sysToolBar.ResumeLayout(false);
            this.sysToolBar.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        public UCRemoteSharer()
        {
            InitializeComponent();

            this.Load += UCRemoteSharer_Load;
        }
        protected RDPSession m_pRdpSession = null;
        void UCRemoteSharer_Load(object sender, EventArgs e)
        {
            if (this.DesignMode)
                return;

            this.tbbStart.Click += tbbStart_Click;
        }

        void tbbStart_Click(object sender, EventArgs e)
        {
            if (this.tbbStart.Text == "开启")
            {
                try
                {
                    m_pRdpSession = new RDPSession();

                    m_pRdpSession.OnAttendeeConnected += new _IRDPSessionEvents_OnAttendeeConnectedEventHandler(OnAttendeeConnected);// 有加入者连接
                    m_pRdpSession.OnAttendeeDisconnected += new _IRDPSessionEvents_OnAttendeeDisconnectedEventHandler(OnAttendeeDisconnected);// 有连接者断开
                    m_pRdpSession.OnControlLevelChangeRequest += new _IRDPSessionEvents_OnControlLevelChangeRequestEventHandler(OnControlLevelChangeRequest);// 连接者控制级别改变，如果只是桌面查看，只需要给 CTRL_LEVEL_VIEW 权限即可

                    m_pRdpSession.Open();

                    IRDPSRAPIInvitation pInvitation = m_pRdpSession.Invitations.CreateInvitation("WinPresenter", "PresentationGroup", "", 5);
                    string invitationString = pInvitation.ConnectionString;
                    System.IO.File.WriteAllText("LocalMachine.xml", invitationString);

                    Logger.Info("Presentation Started. Your Desktop is being shared.");
                    this.tbbStart.Text = "停止";
                }
                catch (Exception ex)
                {
                    Logger.Info("启动异常: " + ex.ToString());
                    this.richTextBox1.Text = "启动异常: " + ex.ToString();
                }
            }
            else
            {
                this.Disconnect();
                this.tbbStart.Text = "开启";
            }
        }

        private void Disconnect()
        {
            if (this.m_pRdpSession != null)
            {
                try
                {
                    m_pRdpSession.Close();
                    Logger.Info("Presentation Stopped.");
                    Marshal.ReleaseComObject(m_pRdpSession);
                    m_pRdpSession = null;
                }
                catch (Exception ex)
                {
                    Logger.Info("关闭异常: " + ex.ToString());
                }
            }
        }

        void OnAttendeeDisconnected(object pDisconnectInfo)
        {
            IRDPSRAPIAttendeeDisconnectInfo pDiscInfo = pDisconnectInfo as IRDPSRAPIAttendeeDisconnectInfo;
            Logger.Info("Attendee Disconnected: " + pDiscInfo.Attendee.RemoteName + Environment.NewLine);
        }

        void OnControlLevelChangeRequest(object pObjAttendee, CTRL_LEVEL RequestedLevel)
        {
            IRDPSRAPIAttendee pAttendee = pObjAttendee as IRDPSRAPIAttendee;
            pAttendee.ControlLevel = RequestedLevel;
        }

        private void OnAttendeeConnected(object pObjAttendee)
        {
            IRDPSRAPIAttendee pAttendee = pObjAttendee as IRDPSRAPIAttendee;
            pAttendee.ControlLevel = CTRL_LEVEL.CTRL_LEVEL_VIEW;
            Logger.Info("Attendee Connected: " + pAttendee.RemoteName + Environment.NewLine);
        }
    }
}
